package com.jackrain.nea.omslocal.Dao;/**
 * Created by Administrator on 2017/4/5.
 */

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;

/**
 * Description:
 * Created with IntelliJ IDEA.
 * User: xyc
 */
@Component
@Slf4j
public class TaoBaoFullQtyDao {

    /**
     * 全量库存同步
     *
     * @param fullQtyArr
     * @param topic
     */
    public void fullQtyStart(JSONArray fullQtyArr, String msgkey, String topic, String tag) throws Exception {
        TaoBaoFullQtyDao taoBaoFullQtyDao = ApplicationContextHandle.getBean(TaoBaoFullQtyDao.class);

        // 会员没有明细表,直接新增主表或更新主表
        for (Object obj : fullQtyArr) {

            JSONObject tempObj = null;
            try {
                // 循环遍历获取会员数据
                tempObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);

                //获取批次
                String batchNo =  tempObj.getString("BatchNo");
                //获取NumIID
                long numIID = TypeUtils.castToLong(tempObj.getString("NumIID"));
                //消息数据
                JSONArray data = (JSONArray) tempObj.get("Data");

                for (int i = 0; i < data.size(); i++) {
                    int status = 0;
                    JSONObject datadetail = data.getJSONObject(i);
                    String extSkuID = datadetail.getString("ExtSkuID");
                    long shopStock = datadetail.getLong("ShopStock");
                    boolean isSuccess = false;
                    try {
                        isSuccess = datadetail.getBoolean("ISSUCCESS");
                    } catch (NullPointerException e) {
                        //  空指针, 没有isSuccess 参数,默认同步失败
                        isSuccess =false;
                    }

                    if(isSuccess){
                        status = 1;
                    }else {
                        status = 2;
                    }
                    String msg = datadetail.getString("MSG");

                    // 根据查询到的 id 更新主表数据
                    taoBaoFullQtyDao.update(batchNo, numIID, extSkuID, shopStock, status, msg);

                }


            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                log.error("msgkey=>"+ msgkey + " topic=>"+ topic + " tag=>"+ tag);
            }

        }

    }

    /**
     * 检查extSkuID是否是处理成功数据
     * @param extSkuID
     * @param errData
     * @return
     */
    private Boolean checkExtShuId(String extSkuID, String errData) {
        boolean isTrue = false;

        if(errData.indexOf(extSkuID)!=-1){
            isTrue = true;
        }else{
            isTrue = false;
        }

        return isTrue;
    }

    @Transactional
    public void update(String batchNo, long numIID, String extSkuID, long shopStock, int status, String msg) throws Exception {
        // 根据批号，NumIID和ExtSkuID修改t_iessynstockqueue中对应的同步数据的同步结果（ShopStock，SynStatus，msg）
        updateStock(batchNo, numIID, extSkuID, shopStock, status, msg);
        System.out.println("全量库存同步：batchNo:"+ batchNo + " numIID:" + numIID + " extSkuID:" + extSkuID +  " shopStock:" + shopStock + " status:" + status + " msg:" + msg);
    }

    /**
     * 更新主表
     * @param batchNo
     * @param numIID
     * @param extSkuID
     * @param shopStock
     * @throws SQLException
     * @throws ParseException
     */
    public void updateStock(String batchNo, long numIID, String extSkuID, long shopStock, int status, String msg) throws SQLException, ParseException {

        Date modifiedDate = new Date(System.currentTimeMillis());

        if(!"0".equals(extSkuID)){
            String sql = "update T_IESSYNSTOCKQUEUE set SYNCNUM = "+shopStock+", SYNSTATUS = ?, ERRORMSG = ?,MODIFIEDDATE = ?  where BATCHNO = ? and NUMIID = ? and EXTSKUID = ?";
            if(status == 2){
                sql = "update T_IESSYNSTOCKQUEUE set SYNCNUM = 0, SYNSTATUS = ?, ERRORMSG = ?,MODIFIEDDATE = ?  where BATCHNO = ? and NUMIID = ? and EXTSKUID = ?";
            }

            QueryEngine.getInstance().executeUpdate(sql, new Object[]{status, msg, modifiedDate,batchNo, numIID, extSkuID});
        }else {
            String sql = "update T_IESSYNSTOCKQUEUE set SYNCNUM = "+shopStock+", SYNSTATUS = ?, ERRORMSG = ?,MODIFIEDDATE = ?  where BATCHNO = ? and NUMIID = ? ";
            if(status == 2){
                sql = "update T_IESSYNSTOCKQUEUE set SYNCNUM = 0, SYNSTATUS = ?, ERRORMSG = ?,MODIFIEDDATE = ?  where BATCHNO = ? and NUMIID = ? ";
            }

            QueryEngine.getInstance().executeUpdate(sql, new Object[]{status, msg, modifiedDate,batchNo, numIID});
        }


    }

}
